﻿(function ($) {


    $.extend(String.prototype, {
        stringFormat: function (args) {
            if (args.length == 0)
                return this;
            var str = this;
            for (var i = 0; i < args.length; i++) {
                var re = new RegExp('\\{' + (i) + '\\}', 'gm');
                str = str.replace(re, args[i]);
            }
            return str;
        }
    });


    $.extend($.fn, {

        ig: function (options) {
            var _this = $(this);

            var api_endpoints = {
                authorize: "https://instagram.com/oauth/authorize/?client_id={0}&redirect_uri={1}&response_type={2}",
                users_infor: "https://api.instagram.com/v1/users/{1}/?access_token={0}&callback=?",
                users_self_feed: "https://api.instagram.com/v1/users/self/feed?access_token={0}&count={1}&callback=?",
                users_media_recent: "https://api.instagram.com/v1/users/{0}/media/recent/?access_token={1}&callback=?"
            };

            var clientid = "8f4cc297898647dbb935db5fcf5e45ea";
            var redirecturl = "http://localhost/IG/Index.html";

            options = options ? options : {};
            $.extend({
                access_token: ""
            }, options);

            var access_token;
            if (!options.access_token) {
                access_token = $.cookie("access_token");
            } else {
                access_token = options.access_token;
            }

            if (access_token) {
                $.cookie("access_token", access_token);

                $.getJSON(api_endpoints.users_self_feed.stringFormat([access_token, 18]), "", function (data) {
                    console.log(data);
                    loadPage(data);
                });
            } else {
                var auth = '<a href="' + api_endpoints.authorize + '">Auth</a>';
                _this.append(auth.stringFormat([clientid, redirecturl, "token"]));
            }

            function loadPage(data) {
                _this.empty();

                loadThumnnailList(data);

                $(".pager #aNext").click(function () {
                    $.getJSON(data.pagination.next_url + "&callback=?", "", function (nextData) {
                        loadPage(nextData);
                    });
                });
            }

            function loadThumnnailList(data) {
                _this.append('<div class="row"></div>');

                $.each(data.data, function (index, item) {
                    var thumbnail = $(formatThumbnail(item));

                    thumbnail.find(".caption img").css("cursor", "pointer").bind("click", function () {
                        _this.empty();
                        $.getJSON(api_endpoints.users_media_recent.stringFormat([item.user.id, access_token]), "", function (data) {
                            loadThumnnailList(data);
                        });
                    });

                    thumbnail.find("img:first").css("cursor", "pointer").bind("click", function () {
                        $("#dlgFullimage").modal();

                        $("#dlgFullimage .modal-title").html(item.caption ? item.caption.text : "");
                        $("#dlgFullimage .modal-body #divFullimage").html("<img src='" + item.images.standard_resolution.url + "'/>");

                        console.log(item);

                        $("#dlgFullimage .modal-body .list-group").empty();
                        $.each(item.comments.data, function (cIndex, cItem) {
                            $("#dlgFullimage .modal-body .list-group").append("<li class='list-group-item'>" + cItem.text + "</li>");
                        });
                    });

                    _this.find(".row:first").append(thumbnail);
                });
            }

            function formatThumbnail(item) {
                //var html = '<div class="col-sm-6 col-lg-3"><div class="thumbnail">{1}<div class="caption"><h5><img src="{2}" width="20px" height="20px" />{0}</h5><div>{3}</div></div></div></div>';
                var html = '<div class="col-sm-6 col-lg-2"><div class="thumbnail">{1}</div></div>';

                var caption = item.caption ? item.caption.text.substr(0, 20) : "";
                var userprofilepicture = item.user.profile_picture;
                var image = "<img src='" + item.images.low_resolution.url + "' />";
                var comment = "likes:<span class='badge'>" + item.likes.count + "</span>&nbsp;&nbsp;&nbsp;comments:<span class='badge'>" + item.comments.count + "</span>";

                var args = [caption, image, userprofilepicture, comment];

                return html.stringFormat(args);
            }
        },

    });
})(jQuery);